<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="银行卡号">
        <el-input
          :value="selectedCard?.cardid || ''"
          disabled
          placeholder="请选择银行卡"
        />
      </el-form-item>

      <el-form-item label="当前余额">
        <el-input
          :value="`¥${Number(selectedCard?.balance || 0).toLocaleString()}`"
          disabled
        />
      </el-form-item>

      <el-form-item label="金额" prop="amount">
        <el-input
          v-model.number="form.amount"
          type="number"
          :placeholder="`请输入${actionTypeText}金额`"
          :min="1"
          :max="actionType === 'withdraw' ? selectedCard?.balance : 999999999"
        >
          <template #prefix>¥</template>
        </el-input>
      </el-form-item>

      <el-form-item v-if="actionType === 'transfer'" label="收款账户" prop="toCardId">
        <el-input
          v-model="form.toCardId"
          placeholder="请输入收款银行卡号"
          maxlength="16"
        />
      </el-form-item>

      <el-form-item label="交易密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入银行卡密码"
          show-password
        />
      </el-form-item>

      <el-form-item v-if="actionType !== 'deposit'" label="备注">
        <el-input
          v-model="form.remark"
          type="textarea"
          :placeholder="`${actionTypeText}备注（可选）`"
          :rows="3"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          确认{{ actionTypeText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { cardApi } from '@/api/card'

export default {
  name: 'QuickActionDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    actionType: {
      type: String,
      default: 'deposit',
      validator: (value) => ['deposit', 'withdraw', 'transfer'].includes(value)
    },
    selectedCard: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref()
    const loading = ref(false)

    const dialogVisible = computed({
      get: () => props.visible,
      set: (value) => emit('update:visible', value)
    })

    const form = ref({
      amount: null,
      toCardId: '',
      password: '',
      remark: ''
    })

    const actionTypeText = computed(() => {
      const texts = {
        deposit: '存款',
        withdraw: '取款',
        transfer: '转账'
      }
      return texts[props.actionType] || '操作'
    })

    const dialogTitle = computed(() => {
      return `快捷${actionTypeText.value}`
    })

    const rules = computed(() => {
      const baseRules = {
        amount: [
          { required: true, message: '请输入金额', trigger: 'blur' },
          { type: 'number', min: 1, message: '金额必须大于0', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入交易密码', trigger: 'blur' }
        ]
      }

      if (props.actionType === 'withdraw') {
        baseRules.amount.push({
          validator: (rule, value, callback) => {
            if (value > Number(props.selectedCard?.balance || 0)) {
              callback(new Error('余额不足'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        })
      }

      if (props.actionType === 'transfer') {
        baseRules.toCardId = [
          { required: true, message: '请输入收款银行卡号', trigger: 'blur' },
          { 
            pattern: /^10103576\d{8}$/, 
            message: '请输入正确的银行卡号格式', 
            trigger: 'blur' 
          }
        ]
      }

      return baseRules
    })

    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        loading.value = true

        let requestData
        let response

        switch (props.actionType) {
          case 'deposit':
            // 存款请求参数：DepositRequest
            requestData = {
              cardid: props.selectedCard.cardid,
              savingid: props.selectedCard.savingid || 1, // 默认存款类型ID
              amount: form.value.amount,
              remark: form.value.remark || ''
            }
            response = await cardApi.deposit(requestData)
            break
            
          case 'withdraw':
            // 取款请求参数：WithdrawRequest
            requestData = {
              cardid: props.selectedCard.cardid,
              amount: form.value.amount,
              pass: form.value.password,
              remark: form.value.remark || ''
            }
            response = await cardApi.withdraw(requestData)
            break
            
          case 'transfer':
            // 转账请求参数：TransferRequest
            requestData = {
              fromCardId: props.selectedCard.cardid,
              password: form.value.password,
              toCardId: form.value.toCardId,
              amount: form.value.amount
            }
            response = await cardApi.transfer(requestData)
            break
        }

        if (response.code === 0) {
          ElMessage.success(`${actionTypeText.value}成功`)
          emit('success')
          handleClose()
        } else {
          ElMessage.error(response.message || `${actionTypeText.value}失败`)
        }

      } catch (error) {
        console.error(`${actionTypeText.value}失败:`, error)
        ElMessage.error(error.message || `${actionTypeText.value}失败`)
      } finally {
        loading.value = false
      }
    }

    const handleClose = () => {
      form.value = {
        amount: null,
        toCardId: '',
        password: '',
        remark: ''
      }
      if (formRef.value) {
        formRef.value.resetFields()
      }
      dialogVisible.value = false
    }

    // 监听对话框显示状态，重置表单
    watch(() => props.visible, (newVal) => {
      if (newVal) {
        form.value = {
          amount: null,
          toCardId: '',
          password: '',
          remark: ''
        }
      }
    })

    return {
      formRef,
      loading,
      dialogVisible,
      form,
      rules,
      actionTypeText,
      dialogTitle,
      handleSubmit,
      handleClose
    }
  }
}
</script>